<?php
class Controller_Storage_Allocate extends Controller_Abstract
{
	function actionCreate()
	{
		$this->_view['title'] = '调拨单新建';
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
	}
	
	function actionCreateSave()
	{
		$this->_view['title'] = '调拨单新建（保存）';
		if ($this->_context->isPOST())
		{
			if ($_POST['start_warehouse_id'] == $_POST['end_warehouse_id'])
			{
				return $this->_redirectMessage('保存失败', '调拨仓和目标仓不能相同', $_SERVER['HTTP_REFERER'], FAILURE);
			}
			else
			{
				if (empty($_POST['product_data']))
				{
					return $this->_redirectMessage('保存失败', '请填写调拨的产品信息', $_SERVER['HTTP_REFERER'], FAILURE);
				}
				else
				{
					$product_data = Q::normalize($_POST['product_data'], "\n");
					$item = array();
					foreach ($product_data as $pd)
					{
						$tmp = Q::normalize($pd, ',');
						$check_in_db = Product_Basic::find('number=?', $tmp[0])->asArray()->getOne();
						if ($check_in_db)
						{
							if (array_key_exists($tmp[0], $item))
							{
								$item[$tmp[0]]['quantity'] += $tmp[1];
							}
							else
							{
								$item[$tmp[0]]['product_basic_id'] = $check_in_db['id'];
								$item[$tmp[0]]['quantity'] = $tmp[1];
							}
						}
					}
					$allocate = array(
						'start_warehouse_id' => $_POST['start_warehouse_id'],
						'end_warehouse_id' => $_POST['end_warehouse_id'],
						'notes' => trim($_POST['notes']),
						'item' => $item
					);
					$result = Warehouse_Allocate::create($allocate);
					if ($result['ack'] == SUCCESS)
					{
						return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::Allocate/List'), $result['ack']);
					}
					else
					{
						return $this->_redirectMessage('部分保存失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
					}
				}
			}
		}
		else
		{
			return $this->_redirectMessage('提交方式有误', '正在返回...', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionList()
	{
		$this->_view['title'] = '调拨单列表';
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$result = Warehouse_Allocate::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$warehouse_allocate = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::Allocate/List', $url_arr));
			$this->_view['warehouse_allocate'] = $warehouse_allocate;
			$this->_view['page'] = $page->getPage();
		}
	}
	
	function actionEdit()
	{
		$this->_view['title'] = '调拨单编辑';
		if ($this->_context->isGET() && ! empty($_GET['id']))
		{
			$warehouse_allocate = Warehouse_Allocate::find('warehouse_allocate.id=? and warehouse_allocate.status=?', $_GET['id'], Q::ini('custom_flag/warehouse_allocate_status/new/value'))
				->joinLeft('user', 'name as make_user_name', 'user.id=warehouse_allocate.make_user_id')
				->asArray()->getOne();
			if ($warehouse_allocate)
			{
				$item = Warehouse_Allocate_Item::find('warehouse_allocate_item.warehouse_allocate_id=?', $_GET['id'])
					->joinLeft('product_warehouse', 'available_quantity', 'product_warehouse.product_basic_id=warehouse_allocate_item.product_basic_id and product_warehouse.warehouse_id=' . $warehouse_allocate['start_warehouse_id'])
					->joinLeft('product_basic', 'name as product_name, number as product_number, purchase_price', 'product_basic.id=warehouse_allocate_item.product_basic_id')
					->asArray()->getAll();
				$this->_view['warehouse_allocate'] = $warehouse_allocate;
				$this->_view['item'] = $item;
				$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
			}
			else
			{
				return $this->_redirectMessage('调拨单不存在或状态有误，请检查调拨单状态', '正在返回...', url('Storage::Allocate/List'), FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('提交方式有误', '正在返回...', url('Storage::Allocate/List'), FAILURE);
		}
	}
	
	function actionEditSave()
	{
		$this->_view['title'] = '调拨单编辑（保存）';
		if ($this->_context->isPOST())
		{
			$allocate = Warehouse_Allocate::find('id=? and status=?', $_POST['warehouse_allocate_id'], Q::ini('custom_flag/warehouse_allocate_status/new/value'))->asArray()->getOne();
			if ($allocate)
			{
				$item = isset($_POST['item']) ? $_POST['item'] : array();
				$warehouse_allocate = array(
					'id' => $_POST['warehouse_allocate_id'],
					'notes' => trim($_POST['notes']),
					'item' => $item
				);
				$result = Warehouse_Allocate::edit($warehouse_allocate);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('编辑成功', '正在返回列表...', url('Storage::Allocate/List'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('编辑失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('编辑失败', '调拨单不存在或者状态不是新单！', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('提交方式有误', '正在返回...', $_SERVER['HTTP_REFERER'], FAILURE);
		}
		
	}
	
	function actionDelete()
	{
		$this->_view['title'] = '调拨单批量删除';
		if (! empty($_GET['ids']))
		{
			$allocate_ids = explode(',', $_GET['ids']);
			$message = array();
			foreach ($allocate_ids as $ai)
			{
				$delete = Warehouse_Allocate::delete($ai);
				if ($delete['ack'] == FAILURE)
				{
					$message [] = $delete['message'];
				}
			}
			if ($message)
			{
				return $this->_redirectMessage('部分删除失败', implode("\n", $message), $_SERVER['HTTP_REFERER'], $delete['ack']);
			}
			else
			{
				return $this->_redirectMessage('删除成功', '正在返回..', $_SERVER['HTTP_REFERER'], $delete['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('删除失败', '提交信息有误，请查看调拨单是否为新单再重试！', url('Storage::Allocate/List'), FAILURE);
		}
	}
	
	function actionProductInfoAjax()
	{
		$this->_view['title'] = '产品信息ajax请求';
		if (! empty($_REQUEST['start_warehouse_id']) & ! empty($_REQUEST['end_warehouse_id']))
		{
			$start_product = Product_Warehouse::search(array('number_or_name' => $_REQUEST['q'], 'warehouse_id' => $_REQUEST['start_warehouse_id']), 0, 20);
			$result = array();
			foreach ($start_product['data'] as $pb)
			{
				//检查目的仓的product_warehouse表是否有产品资料
				$check_end_product = Product_Warehouse::find('warehouse_id=? and product_basic_id=?', $_REQUEST['end_warehouse_id'], $pb['product_basic_id'])->asArray()->getOne();
				if ($check_end_product)
				{
					$result[] = array(
						0 => $pb['number'] . ' ' . $pb['product_basic_name'],
						'id' => $pb['product_basic_id'],
						'number' => $pb['number'],
						'available_quantity' => $pb['available_quantity'],
					);
				}
			}
			echo json_encode($result);
			exit;
		}
	}
	
	function actionCheckAvailableQuantity()
	{
		$this->_view['title'] = '检查产品和可用库存';
		$start_warehouse_id = $_REQUEST['start_warehouse_id'];
		$end_warehouse_id = $_REQUEST['end_warehouse_id'];
		$products = Q::normalize(urldecode($_REQUEST['product_data']), "\n");
		$product = $message = array();
		foreach ($products as $ps)
		{
			$tmp = Q::normalize($ps, ',');
			$check_in_db = Product_Basic::find('number=?', $tmp[0])->asArray()->getOne();
			if ($check_in_db)
			{
				if (array_key_exists($tmp[0], $product))
				{
					$product[$tmp[0]]['quantity'] += $tmp[1];
				}
				else
				{
					$product[$tmp[0]]['product_basic_id'] = $check_in_db['id'];
					$product[$tmp[0]]['quantity'] = $tmp[1];
				}
			}
			else
			{
				$message[] = $tmp[0] . '：不存在系统！';
			}
		}
		$result = Warehouse_Allocate::checkAvialableQuantity($product, $start_warehouse_id, $end_warehouse_id);
		echo json_encode(array_merge($result['message'], $message));exit;
	}
	
	function actionChangeNewToConfirm()
	{
		$this->_view['title'] = '起始仓出库';
		if ($this->_context->isGET())
		{
			$allocate_ids = explode(',', $_GET['ids']);
			$result = Warehouse_Allocate::changeNewToConfirm($allocate_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('起始仓出库成功', '正在返回..', url('Storage::Allocate/List'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('起始仓出库失败', $result['message'], url('Storage::Allocate/List'), $result['ack']);
			}
		}
	}
	
	function actionChangeConfirmToReturn()
	{
		$this->_view['title'] = '调拨返回';
		if ($this->_context->isGET())
		{
			$allocate_ids = explode(',', $_GET['ids']);
			$result = Warehouse_Allocate::changeConfirmToReturn($allocate_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('调拨返回起始仓成功', '正在返回..', url('Storage::Allocate/List'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('调拨返回起始仓失败', $result['message'], url('Storage::Allocate/List'), $result['ack']);
			}
		}
	}
	
	function actionChangeConfirmToArrive()
	{
		$this->_view['title'] = '目标仓入库';
		if ($this->_context->isGET())
		{
			$allocate_ids = explode(',', $_GET['ids']);
			$result = Warehouse_Allocate::changeConfirmToArrive($allocate_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('目标仓入库成功', '正在返回..', url('Storage::Allocate/List'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('目标仓入库失败', $result['message'], url('Storage::Allocate/List'), $result['ack']);
			}
		}
	}
	
	function actionDetail()
	{
		$this->_view['title'] = '调拨单详细';
		if ( ! empty($_GET['id']))
		{
			$columns = array(
				'warehouse_allocate.*',
				'a.name as start_warehouse_name',
				'b.name as end_warehouse_name',
				'c.name as make_user_name'
			);
			$warehouse_allocate = Warehouse_Allocate::find('warehouse_allocate.id=?', $_GET['id'])
				->joinLeft('warehouse as a', '', 'a.id=warehouse_allocate.start_warehouse_id')
				->joinLeft('warehouse as b', '', 'b.id=warehouse_allocate.end_warehouse_id')
				->joinLeft('user as c', '', 'c.id=warehouse_allocate.make_user_id')
				->setColumns($columns)->asArray()->getOne();
			$item = Warehouse_Allocate_Item::find('warehouse_allocate_item.warehouse_allocate_id=?', $_GET['id'])
				->joinLeft('product_basic', 'product_basic.name as product_name, product_basic.number as number', 'product_basic.id=warehouse_allocate_item.product_basic_id')
				->asArray()->getAll();
			Helper_BSS_Normal::getProductImgUrl($item);
			$warehouse_allocate['item'] = $item;
			$this->_view['warehouse_allocate'] = $warehouse_allocate;
		}
		else
		{
			return $this->_redirectMessage('请核对调拨单', "没有该调拨单详细信息", url('Storage::Allocate/List'), FAILURE);
		}
	}
	
	function actionPrintPurchaseProductBarcode()
	{
		$this->_view['title'] = '打印产品条形码';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$order = Warehouse_Allocate::find('id in (?)', $ids)->asArray()->getAll();
			$item = array();
			foreach ($order as $o)
			{
				$warehouse_allocate_item = Warehouse_Allocate_Item::find('warehouse_allocate_item.warehouse_allocate_id=?', $o['id'])
					->joinLeft('product_warehouse as a', '', 'a.product_basic_id=warehouse_allocate_item.product_basic_id and a.warehouse_id=' . $o['end_warehouse_id'])
					->joinLeft('product_warehouse as b', '', 'b.product_basic_id=warehouse_allocate_item.product_basic_id and b.warehouse_id=' . $o['start_warehouse_id'])
					->joinLeft('product_basic', '', 'product_basic.id=a.product_basic_id')
					->setColumns('warehouse_allocate_item.quantity, a.storage_number, a.storage_title, b.shelf_position, product_basic.number')
					->asArray()->getAll();
				$item = array_merge($warehouse_allocate_item, $item);
			}
			OLM_Barcode::productNumberFBA($item);
			exit;
		}
	}
}